package Utils;


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
    private DBUtil(){
    }
    private static volatile MysqlDataSource mysqlDataSource;
    private static volatile Connection connection;

    private static MysqlDataSource getDataSource(){
        if(mysqlDataSource==null){
            synchronized (DBUtil.class){
                if(mysqlDataSource==null){
                    mysqlDataSource=new MysqlDataSource();
                    mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/orderdb2022?characterEncoding=utf8&useSSL=true");
                    mysqlDataSource.setUser("root");
                    mysqlDataSource.setPassword("12345678");
                }
            }
        }
        return mysqlDataSource;
    }

    public static Connection getConnection() throws SQLException {
        MysqlDataSource dataSource=getDataSource();
        return dataSource.getConnection();
    }

    public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection) throws SQLException {
        if(resultSet!=null){
            resultSet.close();
        }
        if(statement!=null){
            statement.close();
        }
        if(connection!=null){
            connection.close();
        }

    }
}
